package org.activemonitoring.datastore.dao;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.activemonitoring.datastore.DataStore;
import org.activemonitoring.datastore.entity.MeasureEntity;
import org.activemonitoring.domain.Measure;
import org.activemonitoring.domain.Measures;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
@Transactional
@Qualifier("default")
public class DataStoreDao implements DataStore {

    protected static final int MAX_RESULTS = 500;

    private static final Logger logger = Logger.getLogger(DataStoreDao.class);

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public void store(Measures measures) {
        if (logger.isDebugEnabled()) {
            logger.debug("Storing " + measures.getMeasure().size() + " measures");
        }
        for (Measure measure : measures.getMeasure()) {
            MeasureEntity entity = new MeasureEntity();
            entity.setCorrelationId(measure.getCorrelationId());
            entity.setModuleName(measure.getModuleName());
            entity.setName(measure.getName());
            entity.setStartTime(new Date(measure.getStartTime()));
            entity.setElapsedTime(measure.getEndTime() - measure.getStartTime());
            entity.setHasError(measure.isHasError());
            if (logger.isTraceEnabled()) {
                logger.trace("Storing measure: " + entity.toString());
            }
            this.entityManager.persist(entity);
        }
    }

    @SuppressWarnings("unchecked")
    public List<MeasureEntity> getMeasures() {
        Query query = this.entityManager.createQuery("from MeasureEntity");
        query.setMaxResults(MAX_RESULTS);
        return query.getResultList();
    }

    public void clear() {
        this.entityManager.createQuery("delete from MeasureEntity").executeUpdate();
    }

    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }
}
